package com.heimali.happyreader.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import android.content.Context;

public class FileUtils {

	public static String readAssetsFile(Context context, String fileName) {
		ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
		try {
			InputStream localInputStream = context.getAssets().open(fileName);
			byte[] bytes = new byte[1024];
			while (true) {
				int i = localInputStream.read(bytes);
				if (i != -1) {
					localByteArrayOutputStream.write(bytes, 0, i);
				} else {
					localByteArrayOutputStream.close();
					localInputStream.close();
					break;
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return localByteArrayOutputStream.toString();
	}

	/**
	 * 取节点大小（文件或文件夹）
	 * 
	 * @param path
	 * @return
	 */
	public static String getNodeSize(String path) {
		File file = new File(path);
		if (file.exists() && file.isDirectory()) {
			return formatFileSize(getDirSize(file));
		} else {
			return String.valueOf(file.length());
		}
	}

	/**
	 * 递归取文件夹大小
	 * 
	 * @param File对象
	 * @return size
	 */
	public static long getDirSize(File folder) {
		long folderSize = 0;

		if (folder.isDirectory()) {
			File[] filelist = folder.listFiles();
			for (int i = 0; i < filelist.length; i++)
				folderSize = folderSize + getDirSize(filelist[i]);
			return folderSize;
		} else
			return folder.length();
	}

	public static String formatFileSize(long fileSize) {// Convert file size
		DecimalFormat df = new DecimalFormat("##0.00");
		String fileSizeString = "";
		long K = 1024, M = 1048576, G = 1073741824;
		if (fileSize < K) {
			fileSizeString = df.format(Rounding(fileSize)) + "B";
		} else if (fileSize < M) {
			fileSizeString = df.format(Rounding((double) fileSize / K)) + "KB";
		} else if (fileSize < G) {
			fileSizeString = df.format(Rounding((double) fileSize / M)) + "MB";
		} else {
			fileSizeString = df.format(Rounding((double) fileSize / G)) + "GB";
		}
		return fileSizeString;
	}

	private static double Rounding(double d) {
		BigDecimal bd = new BigDecimal(d);
		bd.setScale(1, RoundingMode.HALF_UP);
		return bd.floatValue();
	}
}
